<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\Business;

use App\Dao\UserCashDao;
use App\Dao\UserCouponDao;
use App\Dao\UserBankDao;
use App\Dao\UserDao;
use App\Dao\BusinessDao;
use App\Kernel\Util\UserJwtInstance;
use App\Service\Service;

use App\Middleware\Business\BusinessMiddleware;
use App\Service\UploadService;
use Endroid\QrCode\QrCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Middleware;
/**
 * 用户服务
 *
 * @Middleware(BusinessMiddleware::class)
 * @author eug(1196070838@qq.com)
 * @package App\Service\Business
 */
class UserBusinessCashService extends Service
{

    const PENDING = 0; //待处理

    const PROCESSED = 1; //已处理

    const REJECTED = 2; //已拒绝

    /**
     * @Inject
     *
     * @var UserCashDao
     */
      private $dao;

    /**
     * @Inject
     *
     * @var BusinessDao
     */
    private $business_dao;

    /**
     * @Inject
     *
     * @var UserBankDao
     */
    private $user_bank_dao;

    /**
     * @Inject
     *
     * @var UserDao
     */
    private $user_dao;

    /**
     * @Inject
     * @var UploadService
     */
    private $Upload;

    /**
     * 图片保存路径
     *
     *@var string
     */
    public $path = "/home/wwwroot/default/hyperf/hyperf/app/";

    /**
     * 获取提现记录
     * @param array $data
     * @return mixed
     */
    public function getCashInfo(array $data)
    {
        $sum_money = 0;

        $user = UserJwtInstance::instance()->build()->getUser();

        //修改查询时间
        $data['start_time'] = strtotime($data['start_time']);//指定月份的开始时间戳
        $data['end_time'] = mktime(23,59,59,date('m',$data['start_time'])+1,00);  //指定月份月末时间戳

        $result['data'] = $this->dao->getCashInfoByTime($data['start_time'], $data['end_time']);

        foreach ($result['data'] as $key => $value) {
            if ($value->cash_status == $this->dao::CASH_COMPLETE) {//提现完成
                $sum_money += $value->amount;
            }

        }

        $result['money'] = $user->money;//余额
        $result['cumulatived_money'] = $user->cumulatived_money;//累计余额
        $result['sum_money'] = $sum_money;//查询月的提现累计

        return $result;
    }

    /**
     * 发起提现
     *
     * @param array $data
     * @return mixed
     */
    public function cashWithdrawal( array $data)
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        //获取用户的提现银行卡信息
        $bank_info = $this->user_bank_dao->first((int)$data['bank_id']);

        $money = $user->money - $data['amount'];

        if ( $money < 0 ) {
            $this->error('USER.NOT_MONEY');
        }

        $cumulatived_money = $user->cumulatived_money + $data['amount'];//累计提现余额

        $order_sn = date('YmdHis',time()).substr(strval(uid()+100000000),1,9).rand(100000,999999);//订单编号

        $save_data = [
            'user_id' => $user->id,
            'amount' => $data['amount'],
            'bank_name' => $bank_info['bank_name'],
            'bank_account' => $bank_info['bank_account'],
            'bank_realname' => $bank_info['name'],
            'bank_idcard' => $bank_info['idcard'],
            'bank_phone' => $bank_info['phone'],
            'status' => self::PENDING,
            'start_time' => time(),
            'cash_status' => $this->dao::CASH_IN,
            'money' => $money,
            'order_sn' => $order_sn,
        ];

        $result = $this->dao->create($save_data);

        !$result && $this->error();

        $update_data = [
            'money' => $money,
            'cumulatived_money' => $cumulatived_money,
        ];

        $update_res = $this->user_dao->update($update_data);

        !$update_res && $this->error();

        $return_data['id'] = $result['id'];
        return $return_data;

    }

    /**
     * 获取一条提现信息
     *
     * @param array $data
     * @return mixed
     */
    public function getCashOne(array $data)
    {

        $result = $this->dao->first($data['id']);

        !$result && $this->error();

        $return_data['id'] = $result['id'];
        $return_data['amount'] = $result['amount'];
        $return_data['bank_name'] = $result['bank_name'];
        $return_data['bank_account'] = $result['bank_account'];
        $return_data['start_time'] = $result['start_time'];
        $return_data['arrival_time'] = $result['arrival_time'];
        $return_data['order_sn'] = $result['order_sn'];
        $return_data['cash_status'] = $result['cash_status'];
        $return_data['cash_status_text'] = $result['cash_status_text'];

        return $return_data;
    }

    /**
     * 检查密码
     *
     * @param array $data
     * @return array
     */
    public function checkPwd(array $data)
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        //验证密码
        if( !password_verify( $data['pwd'], $user->login_pwd ) ) {
            $this->error('USER.REGISTER_FAIL');
        }
    }

    /**
     * 获取收款码
     *
     * @return string
     */
    public function getQrCode(  )
    {
        $url = gConfig('sacn_url','');
        $qrCode_url = [];
        $user = UserJwtInstance::instance()->build()->getUser();
        $business = $user->business;

        //存在收款码，返回收款码路径
        if ($business->receivabled_qrcode) {
            $qrCode_url['receivabled_qrcode'] = $business->receivabled_qrcode;
            return $qrCode_url;
        }

        //不存在收款码，生成收款码
        $content = $url.'?business_id='.$business->id;

        $qrCode = new QrCode($content);//开启二维码

        $path_name = $this->path.'/public/images/'.rand(10000, 99999).'.png'; //路径

        $qrCode->writeFile($path_name); //生成二维码

        $file_name = md5_file($path_name).'.png'; //生成图片名称

        $img_url = $this->Upload->qrCodeUpload($path_name, $file_name); //上传oss

        $qrCode_url['receivabled_qrcode'] = $url.'/'.$img_url;//生成全路径

        //将路径保存在数据库中
        $this->business_dao->update((int)$business->id,$qrCode_url);

        unlink($path_name);

        return $qrCode_url;
    }

}